<?php

    /**
     * @package      Modules
     * @subpackage   Widgets_Classes_Db
     *
     * @license      GNU Lesser General Public Licence see LICENCE-LGPL file or http://www.gnu.org/licenses/lgpl.html
     */
    class DbWidget extends BaseDbWidget
    {

    ////////////////////////////////////////////////////////////////////////////
    //                                Methods                                 //
    ////////////////////////////////////////////////////////////////////////////

        /**
         * Retrieves params
         * 
         * @param       DbAdmin     $admin
         */
        public function getParams(DbAdmin $admin)
        {
            return DbWidgetParam::getValues($this, $admin);
        }

        /**
         * Adds widget for admin
         *
         * @param       DbAdmin         $admin
         */
        public function addForAdmin(DbAdmin $admin)
        {
            $registred = Doctrine_Query::create()
                            ->from('DbAdminWidget aw')
                            ->where('aw.widget_id = ?', $this->id)
                            ->addWhere('aw.admin_id = ?', $admin->id)
                            ->fetchOne();

            if ($registred) {
                return;
            }

            $adminWidget            = new DbAdminWidget();
            $adminWidget->status    = DbBase::ENABLED;
            $adminWidget->display   = true;
            $adminWidget->DbWidget  = $this;
            $adminWidget->DbAdmin   = $admin;
            $adminWidget->save();
        }

        /**
         * Deletes widget for admin
         *
         * @param       DbAdmin         $admin
         */
        public function deleteFromAdmin(DbAdmin $admin)
        {
            $registred = Doctrine_Query::create()
                            ->from('DbAdminWidget aw')
                            ->where('aw.widget_id = ?', $this->id)
                            ->addWhere('aw.admin_id = ?', $admin->id)
                            ->fetchOne();

            if (!$registred) {
                return;
            }

            $registred->delete();

            $params = Doctrine_Query::create()
                        ->from('DbAdminWidgetParam awp')
                        ->leftJoin('awp.DbWidgetParam wp')
                        ->leftJoin('wp.DbWidget w')
                        ->where('awp.admin_id = ?', $admin->id)
                        ->addWhere('w.id = ?', $this->id)
                        ->execute();

            foreach ($params as $param) {
                $param->delete();
            }
        }
    }